import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Select, Upload, message, Icon, Avatar } from 'antd';
import React, { Component, Fragment, useState, useEffect } from 'react';
import { connect } from 'dva';
import GeographicView from './GeographicView';
import PhoneView from './PhoneView';
import styles from './BaseView.less';
import { updateUserInfo } from "../service";
import { PARAMS_MAP, STATIC_URL, HTTP_STATUS } from "@/generic/ConfigParams";

const FormItem = Form.Item;
const { Option } = Select; // 头像组件 方便以后独立，增加裁剪之类的功能

const MAX_IMG_SIZE = { size: 2 * 1024 * 1024, format: "2M" };

const AvatarView = ({ avatar, uploadProps }) => (
  <Fragment>
    <div className={styles.avatar_title}>Avatar</div>
    <Avatar className={styles.avatar} src={avatar} />
    <Upload {...uploadProps}>
      <div className={styles.button_view}>
        <Button>
          <Icon type="upload" />
          更换头像
        </Button>
      </div>
    </Upload>
  </Fragment>
);

const validatorGeographic = (_, value, callback) => {
  const { province, city } = value;

  if (!province.key) {
    callback('Please input your province!');
  }

  if (!city.key) {
    callback('Please input your city!');
  }

  callback();
};

const validatorPhone = (rule, value, callback) => {
  const values = value.split('-');

  if (!values[0]) {
    callback('Please input your area code!');
  }

  if (!values[1]) {
    callback('Please input your phone number!');
  }

  callback();
};

class BaseView extends Component {
  view = undefined;

  state = {
    avatar: '',
    uploadProps: {},
  };

  componentDidMount() {
    
    const uploadProps = {
      key: "0",
      accept: "image/*",
      showUploadList: false,
      beforeUpload: this.beforeUpload,
      customRequest: (opts) => this.fileUpload(opts),
    }
    this.setBaseInfo();
    this.setState({
      uploadProps,
      avatar: this.getAvatarURL(),
    })
  }

  setBaseInfo = () => {
    // console.log('====>> setBaseInfo', this.props)
    const { currentUser, form } = this.props;

    if (currentUser) {
      Object.keys(form.getFieldsValue()).forEach(key => {
        const obj = {};
        obj[key] = currentUser[key] || null;
        form.setFieldsValue(obj);
      });
    }
  };

  getAvatarURL = (newAvatar) => {
    const { currentUser } = this.props;
    
    if (newAvatar) return newAvatar;  // 因为图片路径不变，故用此 临时代替法。

    if (currentUser) {
      if (currentUser.avatar) {
        return `${STATIC_URL}${currentUser.avatar}`;
      }

      return 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
    }

    return '';
  }

  beforeUpload = (file) => { // 此处做文件的大小检查与限制

    if (file.size > MAX_IMG_SIZE.size) {
      message.warn(`文件不得超过${MAX_IMG_SIZE.format}！`);
      return false;
    }
  }

  fileUpload = (opts) => {

    const { dispatch, currentUser } = this.props;
    
    const hide = message.loading('正在上传，请稍候。');
    const fileName = opts.file.name;
    const reader = new FileReader();
    reader.readAsArrayBuffer(opts.file);
    reader.onload = async e => {
      
      const response = await dispatch({ 
        type: 'accountSettings/uploadAvatar', 
        payload: { file: e.target.result, id: currentUser.userid} 
      });
      hide();
      if (response.ok) {
        message.success(`${fileName} 上传成功！`);

        const tempReader = new FileReader();  // 因为图片路径不变，故用此 临时代替法。
        tempReader.readAsDataURL(opts.file);  // 读出本地文件的内容。 | data: URL格式的Base64字符串。
        tempReader.onload = e => {
          this.setState({ avatar: this.getAvatarURL(e.target.result) });
        }
      }
      else {
        message.error(`${fileName}上传失败：${HTTP_STATUS[response.status]}！`);
      }
    }

  }

  getViewDom = ref => {
    this.view = ref;
  };

  handlerSubmit = event => {
    event.preventDefault();
    const { form, currentUser} = this.props;
    form.validateFields( async err => {
      if (!err) {
        let hide = message.loading("更新中，请稍候。")
        const params = {};
        const { dispatch } = this.props;
        dispatch({
          type: "accountSettings/saveCurrentUser",
          payload: "321"
        })
        for (const key in form.getFieldsValue()) {
          if (form.isFieldTouched(key)) {  // 判断哪些值更改了
            params[PARAMS_MAP[key]] = form.getFieldValue(key);
          }
        }
        console.log("===>>> params", params)
        const response = await updateUserInfo(params, currentUser.userid);
        hide();
        if (response.ok) {
          message.success('更新成功！');
          return;
        }
        message.error(`更新失败！code：${response.status}`)
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator }, dispatch = () => { },
    } = this.props;

    const { avatar, uploadProps } = this.state;

    console.log('==>> avatar', avatar)
    
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form layout="vertical" hideRequiredMark>
            <FormItem label="昵称">
              {getFieldDecorator('nickName', {
                rules: [
                  {
                    required: true,
                    message: '请输入您的昵称!',
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="姓名">
              {getFieldDecorator('trueName', {
                rules: [
                  {
                    message: '请输入您的姓名!',
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="邮箱">
              {getFieldDecorator('email', {
                rules: [
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="个人简介">
              {getFieldDecorator('profile', {
                rules: [
                  {
                    message: '请输入个人简介!',
                  },
                ],
              })(
                <Input.TextArea placeholder="个人简介" rows={4} />,
              )}
            </FormItem>
            <FormItem label="国家/地区">
              {getFieldDecorator('country', {
                rules: [
                  {
                    // required: true,
                    message: '请输入您的国家或地区',
                  },
                ],
              })(
                <Select
                  style={{
                    maxWidth: 220,
                  }}
                >
                  <Option value="China">中国</Option>
                </Select>,
              )}
            </FormItem>
            {/* <FormItem label="所在省市">
              {getFieldDecorator('geographic', {
                rules: [
                  {
                    required: true,
                    message: '请输入您的所在省市',
                  },
                  {
                    validator: validatorGeographic,
                  },
                ],
              })(<GeographicView />)}
            </FormItem> */}
            <FormItem label="街道地址">
              {getFieldDecorator('address', {
                rules: [
                  {
                    // required: true,
                    message: '请输入您的街道地址',
                  },
                ],
              })(<Input />)}
            </FormItem>
            {/* <FormItem label="联系电话">
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: '请输入您的联系电话',
                  },
                  {
                    validator: validatorPhone,
                  },
                ],
              })(<PhoneView />)}
            </FormItem> */}
            <Button type="primary" onClick={this.handlerSubmit}>
              更新基本信息
            </Button>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={avatar} uploadProps={uploadProps}/>
        </div>
      </div>
    );
  }
}

export default connect(({ accountSettings, user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(BaseView));
